package day4;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

//反射测试方法
public class TextMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //1.获取类对象
        Class c = Class.forName("day4.Persion");
        //2.获取Persion的所有方法,私有方法要设置权限
        Method[] ms = c.getDeclaredMethods();
        for (Method m : ms) {
            m.setAccessible(true);
            String name = m.getName();
            Class<?>[] cs = m.getParameterTypes();
            Class<?> returnType = m.getReturnType();
            System.out.println("方法:" + name + ",参数:" + Arrays.toString(cs) + ",返回类型:" + returnType);
            System.out.println(m);
        }

        //获取Persion的所有方法，包括继承的父类方法
        System.out.println("------------------------");
        Method[] ms1 = c.getMethods();
        for (Method method : ms1) {
            method.setAccessible(true);
            System.out.println(method);
        }

        //获取一个方法    然后进行调用
        //test();
        //test("aa");
        //test("b", 12, true);
        Method m1 = c.getDeclaredMethod("test1");
        Method m2 = c.getDeclaredMethod("test2", String.class, Integer.class);
        Method m3 = c.getDeclaredMethod("test3", int.class, int.class);
        m1.setAccessible(true); //开启权限  默认false
        m2.setAccessible(true); //开启权限  默认false

        //调用方法      m1.invoke(对象,方法调用的实参);
        Persion p = new Persion();
        Object value1 = m1.invoke(p);
        Object value2 = m2.invoke(p, "haha", 23);
        Object value3 = m3.invoke(p, 10, 20);

        System.out.println(value1 + " " + value2 + " " + value3);

    }

    //如果方法的参数、个数不确定(0-n个参数)
    //如果类型也不确定  可以定义Object
    //String ... a 表示可变长参数(本质上就是数组)
    public static void test(Object... a) {
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
